#include <math.h>
#include <wchar.h>
#include <ft2build.h>
#include FT_FREETYPE_H


#include "fb.h"
#define WIDTH   800 
#define HEIGHT  1280

FT_Library lib;
FT_Face face;

static void draw_bitmap(FT_Bitmap*  bitmap, FT_Int x, FT_Int y, int fcolor, int bcolor)
{
	FT_Int  i, j;
	FT_Int  x_max = bitmap->width;
	FT_Int  y_max = bitmap->rows;

	for ( j = 0; j < y_max; j++) {
		for ( i =  0; i < x_max; i++) {
			char c = bitmap->buffer[j * bitmap->width + i];
			int color = (int)((c << 24) | (c << 16) | (c << 8)) | 0xff;
			osd_draw_color(y + j, x + i, 1, 1, c ? (fcolor & color) : bcolor);
		} 
	}
}

int text_font_load(const char *file)
{
	if (FT_Init_FreeType(&lib)) 
		return printf("freetype init error!\n");
	printf("freetype init ...\n");

	if (FT_New_Face(lib, file, 0, &face)) 
		return printf("freetype new face error!\n");
	printf("freetype new face...\n");

	return 0;
}


void show_text_base(int x, int y, int fcolor, int bcolor, const char *txt, int font_size)
{
	int n;
	FT_Vector     pen;                    /* untransformed origin  */
	FT_GlyphSlot  slot;

	slot = face->glyph;
	pen.x = x * 64;
	pen.y = (HEIGHT - y) * 64;

	FT_Set_Pixel_Sizes(face, font_size, 0);   /* set character size */

	for (n = 0; n < strlen(txt); n++) {
		/* set transformation */
		FT_Set_Transform(face, 0, &pen);

		/* load glyph image into the slot (erase previous one) */
		if (FT_Load_Char(face, txt[n], FT_LOAD_RENDER))
			continue;                 

		/* now, draw to our target surface (convert position) */
		draw_bitmap(&slot->bitmap, slot->bitmap_left, HEIGHT - slot->bitmap_top, fcolor, bcolor);

		/* increment pen position */
		pen.x += slot->advance.x;
		pen.y += slot->advance.y;
	}
}

void show_text(int x, int y, int color, const char *txt, int font_size)
{
	show_text_base(x, y, color, 0x0, txt, font_size);
}

#if 01
int main(int argc, char** argv)
{
	if ( argc != 3 ) 
		return fprintf (stderr, "usage: %s font sample-text\n", argv[0]);

	fb_init();
	text_font_load(argv[1]);
	int major = 0;
	int minor = 0;
	int patch = 0;
	char libVersion[50] = {'\0'};
  	FT_Library_Version(lib, &major, &minor, &patch);
	sprintf(libVersion, "freetype Version %d.%d.%d", major, minor, patch);
	show_text(100, 100, 0x00FF00, libVersion, 40);

	show_text(100, 200, 0xff0000, argv[2], 40);
	return 0;
}
#endif
